<template>
  <div class="simple-container">
    <!-- 简约背景图 -->
    <div class="simple-background"></div>

    <!-- 内容区域 -->
    <div class="simple-content">
      <!-- 标题区域 -->

      <!-- 登录框（保持原有功能） -->
      <div class="simple-login-box">
        <h3>账号密码登录</h3>

        <el-form
            :model="user"
            :rules="rules"
            ref="loginForm"
            @submit.prevent="login"
        >
          <el-form-item prop="username">
            <el-input
                v-model="user.username"
                placeholder="用户名"
                prefix-icon="User"
                class="simple-input"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="user.password"
                type="password"
                placeholder="输入密码"
                prefix-icon="Lock"
                show-password
                class="simple-input"
            />
          </el-form-item>


          <el-form-item>
            <el-button
                type="primary"
                native-type="submit"
                class="simple-submit-btn"
                :loading="loading"
                :disabled="isLocked"
            >
              登录
            </el-button>
          </el-form-item>

          <div class="simple-options">
            <el-link @click="goToRegister">新用户注册</el-link>
          </div>

          <div class="simple-agreement">
            <el-checkbox v-model="agreed">登录代表同意《用户协议》及《隐私政策》</el-checkbox>
          </div>

          <div v-if="isLocked" class="simple-lock-message">
            登录失败次数过多，请 {{ remainingTime }} 秒后再试。
          </div>
        </el-form>
      </div>

      <!-- 页脚 -->
      <div class="simple-footer">
        <p>Copyright © 2002-2025.版权所有 请根据本标准发布的信息</p>
      </div>

      <!-- 管理员登录链接 -->
      <div class="simple-admin-login">
        <el-link type="info" @click="showAdminDialog">管理员登录</el-link>
      </div>
    </div>

    <!-- 管理员登录对话框（保持原有） -->
    <el-dialog v-model="adminDialogVisible" title="管理员登录" width="30%">
      <el-form :model="adminForm" :rules="adminRules" ref="adminFormRef">
        <el-form-item prop="password">
          <el-input
              v-model="adminForm.password"
              type="password"
              placeholder="请输入管理员密码"
              show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adminDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="adminLogin">登录</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const loginForm = ref(null);
const loading = ref(false);
const rememberMe = ref(false);
const agreed = ref(false);

// 管理员登录相关代码
const adminDialogVisible = ref(false);
const adminForm = ref({ password: '' });
const adminFormRef = ref(null);

const user = ref({
  username: '',
  password: ''
});

// 登录相关状态
const isLocked = ref(false);
const remainingTime = ref(0);

const adminRules = {
  password: [
    { required: true, message: '请输入管理员密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
};

const showAdminDialog = () => {
  adminDialogVisible.value = true;
};

const adminLogin = async () => {
  try {
    const valid = await adminFormRef.value.validate();
    if (valid) {
      const response = await axios.post('8080/admin/login', {
        password: adminForm.value.password
      });

      if (response.data.state === 200) {
        localStorage.setItem('adminToken', response.data.data.token);
        router.push('/admin/dashboard');
        ElMessage.success('管理员登录成功');
      } else {
        ElMessage.error(response.data.msg);
      }
    }
  } catch (error) {
    ElMessage.error('登录失败');
  }
};

const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ]
};

const login = () => {
  if (!agreed.value) {
    ElMessage.warning('请先同意用户协议和隐私政策');
    return;
  }

  axios.post(BASE_URL+'/user/login', user.value, {withCredentials: true})
      .then((response) => {
        if (response.data.state === 200) {
          ElMessage.success('登录成功!');
          localStorage.setItem('token', response.data.data.token);
          localStorage.setItem('user', JSON.stringify(response.data.data));
          if (rememberMe.value) {
            localStorage.setItem('rememberMe', 'true');
          }
          window.dispatchEvent(new Event('storage'));
          router.push('/');
        } else {
          if (response.data.state === 6666) {
            isLocked.value = true;
            const match = response.data.data.match(/(\d+)/);
            remainingTime.value = match ? parseInt(match[1], 10) : 0;
            startCountdown();
          } else if (response.data.state === 1001) {
            ElMessage.error('密码错误，请重新输入');
          } else if (response.data.state === 4445) {
            ElMessage.error('用户不存在，请检查用户名');
          } else {
            ElMessage.error(response.data.msg);
          }
          user.value = {username: '', password: ''};
        }
      }).catch(error => {
    console.error('登录请求失败:', error);
    ElMessage.error('网络或服务器错误');
  });
};

const startCountdown = () => {
  let countdown = remainingTime.value;
  const interval = setInterval(() => {
    if (countdown <= 0) {
      clearInterval(interval);
      isLocked.value = false;
      remainingTime.value = 0;
    } else {
      countdown--;
      remainingTime.value = countdown;
    }
  }, 1000);
};

const goToRegister = () => {
  router.push('/register');
};

const goToForget = () => {
  router.push('/forget-password');
};
</script>

<style scoped>
.simple-container {
  display: flex;
  min-height: 100vh;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  position: relative;
}

.simple-background {
  position: fixed;
  top: 10%;
  left: 0;
  width: 100%;
  height: 80%;
  background-image: url('@/assets/loginpicture.png');
  background-size: cover;
  background-position: center;
  opacity: 0.7;  /* 调整透明度 */
  z-index: 0;   /* 确保在最底层 */
}

.simple-login-box {
  /* 其他样式保持不变 */
  z-index: 1;   /* 确保登录框在上层 */
  background: rgba(255, 255, 255, 0.95); /* 明确设置半透明白色 */
}

.simple-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding-right: 10%;
}

.simple-header {
  text-align: right;
  margin-bottom: 40px;
  color: #333;
  width: 100%;
  padding-right: 20px;
}

.simple-header h1 {
  font-size: 32px;
  margin-bottom: 10px;
  font-weight: bold;
}

.simple-header h2 {
  font-size: 18px;
  color: #666;
  margin-bottom: 15px;
}

.simple-header p {
  font-size: 14px;
  color: #888;
  line-height: 1.6;
}

.simple-login-box {
  width: 400px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-top: 10vh;
  margin-bottom: 10vh;
}

.simple-login-box h3 {
  text-align: center;
  margin-bottom: 25px;
  font-size: 18px;
  color: #333;
}

.simple-input :deep(.el-input__inner) {
  height: 48px;
  padding-left: 40px;
}

.simple-remember {
  margin: 15px 0 25px;
}

.simple-submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
}

.simple-options {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}

.simple-agreement {
  margin-top: 20px;
  font-size: 12px;
}

.simple-lock-message {
  text-align: center;
  color: #f56c6c;
  margin-top: 15px;
  font-size: 14px;
}

.simple-footer {
  margin-top: auto;
  text-align: center;
  font-size: 12px;
  color: #888;
  width: 100%;
  padding-bottom: 20px;
}

.simple-admin-login {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

@media (max-width: 768px) {
  .simple-content {
    padding: 20px;
    align-items: center;
  }

  .simple-header {
    text-align: center;
    padding-right: 0;
  }

  .simple-login-box {
    width: 100%;
    padding: 20px;
    margin-top: 5vh;
    margin-bottom: 5vh;
  }

  .simple-background {
    top: 5%;
    height: 90%;
  }
}
</style>